package com.fowo.api.sys.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fowo.api.common.model.R;
import com.fowo.api.sys.entity.SysTask;
import com.fowo.api.sys.model.SysTaskItemVo;
import com.fowo.api.sys.model.SysTaskSearch;
import com.fowo.api.sys.model.SysTaskVo;
import com.fowo.api.sys.service.SysTaskExecutionService;
import com.fowo.api.sys.service.SysTaskService;
import com.fowo.api.user.model.JwtUserInfo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/api/sys/task")
@Tag(name = "系统任务")
public class SysTaskController {

    @Resource
    private SysTaskService sysTaskService;
    @Resource
    private SysTaskExecutionService sysTaskExecutionService;

    @GetMapping("page")
    @Operation(summary = "分页查询")
    public R<Page<SysTaskItemVo>> pageSearch(SysTaskSearch search) {
        return R.data(() -> sysTaskService.pageSearch(search));
    }

    @GetMapping()
    @Operation(summary = "查询")
    public R<List<SysTaskItemVo>> search(SysTaskSearch search) {
        return R.data(() -> sysTaskService.search(search));
    }

    @GetMapping("{id}")
    @Operation(summary = "获取单个详情")
    public R<SysTaskVo> getById(@PathVariable Long id) {
        return R.data(() -> sysTaskService.getVoById(id));
    }

    @PostMapping
    @Operation(summary = "新增")
    public R create(@RequestBody @Validated SysTaskVo sysTaskVo) {
        return R.ok(() -> sysTaskService.create(sysTaskVo));
    }

    @PutMapping
    @Operation(summary = "更新")
    public R update(@RequestBody @Validated SysTaskVo sysTaskVo) {
        return R.ok(() -> sysTaskService.update(sysTaskVo));
    }

    @DeleteMapping("{id}")
    @Operation(summary = "删除")
    public R delete(@PathVariable Long id) {
        return R.ok(() -> sysTaskService.delete(id));
    }

    @PostMapping("{id}/start")
    @Operation(summary = "立即执行")
    public R start(@PathVariable Long id, JwtUserInfo jwtUserInfo) {
        return R.ok(() -> sysTaskExecutionService.start(jwtUserInfo.getDisplayName(), id));
    }

    @PostMapping("{id}/stop")
    @Operation(summary = "停止执行")
    public R stop(@PathVariable Long id, JwtUserInfo jwtUserInfo) {
        return R.ok(() -> sysTaskExecutionService.stop(jwtUserInfo.getDisplayName(), id));
    }

    @DeleteMapping("{id}/terminate")
    @Operation(summary = "终止任务")
    public R terminate(@PathVariable Long id) {
        return R.run(() -> sysTaskService.terminate(id));
    }
}
